//
//  DDExchangeInformation.m
//  MyClouds
//
//  Created by sarah doo on 13-8-11.
//  Copyright (c) 2013年 sarah doo. All rights reserved.
//

#import "DDExchangeInformation.h"
#import "NSMutableData+Replace.h"
#import "NSString+md5.h"
@implementation DDExchangeInformation



- (id)initWithData:(NSData *)data {
    self = [super initWithData:data];
    return self;
}
- (id)initWithCloudId:(NSString *)cloudId andName:(NSString *)cloudName andType:(NSString *)typeName{
    self = [super init];
    if(self){
//        cloudName = [cloudName stringByAppendingFormat:@"%c%c%c%c",0x01,0x01,0x01,0x01];
//        Byte buffer [4];
//        for (int i = 0; i < 4 ; i++) {
//            buffer[i] = 0;
//        }
        
        [entity replaceByString:cloudId length:CLOUD_ID_LENGTH * 2  offset:HEADER_LENGTH];
        [entity replaceByString:cloudName length:CLOUD_NAME_LENGTH * 2 offset:(HEADER_LENGTH + CLOUD_NAME_LENGTH *2)];
        [entity replaceByString:typeName length:DEVICE_TYPE_LENGTH * 2 offset:(HEADER_LENGTH + CLOUD_NAME_LENGTH * 4)];
        [self setCmd:CloudCmd_ExchangeInformation];
        int exchangeInfoLength = HEADER_LENGTH + CLOUD_ID_LENGTH * 2 + CLOUD_NAME_LENGTH * 2 + DEVICE_TYPE_LENGTH * 2;
        [self setLength:exchangeInfoLength];
        [self setCrc:[self crcs:entity withLength:exchangeInfoLength]];
    }
    return self;
}


- (NSString *)getCloudId
{
    NSRange range;
    range.location = HEADER_LENGTH;
    range.length = CLOUD_ID_LENGTH * 2;
    NSData * cloudIdData = [entity subdataWithRange:range];
    NSString *cloudId = [[NSString alloc]initWithBytes:[cloudIdData bytes] length:CLOUD_ID_LENGTH*2 encoding:NSASCIIStringEncoding];
    return cloudId;
}

- (NSString *)getCloudName
{
    NSRange range;
    range.location = HEADER_LENGTH + CLOUD_ID_LENGTH * 2;
    range.length = CLOUD_NAME_LENGTH * 2;
    NSData *cloudNameData = [entity subdataWithRange:range];
    
    Byte bytes[] = {255,254};
    bytes[0] = 255;
    bytes[1] = 254;
    NSMutableData *headData = [[NSMutableData alloc]initWithBytes:bytes length:2];
    [headData appendData:cloudNameData];
    NSString* name = [[NSString alloc] initWithData:headData encoding:NSUnicodeStringEncoding];
//    NSString* testName = [self dataToString:cloudNameData];
//    NSString* testName = [[NSString alloc]initWithBytes:[cloudNameData bytes] length:DEVICE_TYPE_LENGTH*2 encoding:NSASCIIStringEncoding];
//    testName = [testName addHeadASCII];
    
    return name;
}

- (NSString *)getTypeName
{
    NSRange range;
    range.location = HEADER_LENGTH + CLOUD_NAME_LENGTH * 2 + CLOUD_ID_LENGTH * 2;
    range.length = DEVICE_TYPE_LENGTH * 2;
    NSData *typeNameData = [entity subdataWithRange:range];
    NSString *typeName = [[NSString alloc]initWithBytes:[typeNameData bytes] length:DEVICE_TYPE_LENGTH*2 encoding:NSASCIIStringEncoding];
    return typeName;
}

@end
